import axios, { AxiosResponse } from 'axios';

// import qs from 'qs'
import { ElMessage } from 'element-plus'
import useSettingsStore from '@/store/modules/settings'
import useUserStore from '@/store/modules/user'

const api : any = axios.create({
	baseURL: (import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true') ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
	timeout: 1000 * 60,
	responseType: 'json',
})

api.interceptors.request.use((request : any) => {
	// 全局拦截请求发送前提交的参数
	const settingsStore = useSettingsStore()
	const userStore = useUserStore()
	// 设置请求头
	if (request.headers) {
		request.headers['Accept-Language'] = settingsStore.settings.app.defaultLang
		// request.headers.Authorization = `Bearer ${userStore.token}`
		if (userStore.isLogin) {
			request.headers.Token = userStore.token
			request.headers.Authorization = `Bearer ${userStore.token}`
		}
	}
	// 是否将 POST 请求参数进行字符串化处理
	if (request.method === 'post') {
		// request.data = qs.stringify(request.data, {
		//   arrayFormat: 'brackets',
		// })
	}
	return request
},
)

api.interceptors.response.use(
	(response : any) => {
		let res_data : any = response.data
		if (res_data.code === 401) {
			useUserStore().logout()
			return false
		}
		console.log(res_data.code, 555)
		if (res_data.code == -1) {
			ElMessage.error(res_data.msg)
		}
		function checkDataType(data : any) {
			if (Array.isArray(data)) {
				return 'Array'
			}
			else if (typeof data === 'object' && data !== null) {
				return 'Object'
			}
			else {
				return 'Neither an array nor an object'
			}
		}
		switch (checkDataType(res_data.data)) {
			case 'Array':
				return Promise.resolve(res_data)
				break
			case 'Object':
				return Promise.resolve(res_data.data)
				break
			default:
				break
		}
	},
	(error : any) => {
		let message = error.message
		if (message === 'Network Error') {
			message = '后端网络故障'
		}
		else if (message.includes('timeout')) {
			message = '接口请求超时'
		}
		else if (message.includes('Request failed with status code')) {
			message = `接口${message.substr(message.length - 3)}异常`
		}
		ElMessage({
			message,
			type: 'error',
		})
		return Promise.reject(error)
	},
)

export default api